/*
 * Copyright (c) 2010, 2012 Luan Nguyen Thanh. All rights reserved.
 * 
 * This code is written by Luan Nguyen Thanh, with any partners involved.
 * The unauthorized use of this code should not be permitted!
 */
package MyIM.client.view.form;

import MyIM.client.engine.Engine;
import MyIM.client.view.component.ErrorTooltip;
import MyIM.client.view.component.HintTextField;
import MyIM.client.view.component.JTKButton;
import MyIM.client.view.lnf.MetroStyle;
import MyIM.utilities.Status;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author Luan Nguyen Thanh <tklarryonline@gmail.com>
 */
public class Dialog_Register extends JDialog implements ActionListener {

    private HintTextField txtUsername, txtDisplayName;
    private JPasswordField txtPassword, txtConfirmPassword;
    private JTextField txtFilePath;
    private JButton btnSave, btnCancel, btnFileChooser;
    private ErrorTooltip tipUsername, tipPassword, tipConfirmPwd;
    private Engine engine;
    private FileFilter imageFilter = new FileFilter() {

        private final String png = "png";
        private final String jpg = "jpg";
        private final String jpeg = "jpeg";

        // Accept only the CSV file
        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return true;
            }

            String ext = getExtension(pathname);
            if (ext != null) {
                return (ext.equals(this.png)
                        || ext.equals(this.jpeg)
                        || ext.equals(this.jpg));
            }

            return false;
        }

        public String getDescription() {
            return "Accepted image file (*.png, *.jpg, *.jpeg)";
        }

        private String getExtension(File f) {
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');

            if (i > 0 && i < s.length() - 1) {
                ext = s.substring(i + 1).toLowerCase();
            }

            return ext;
        }
    };

    public Dialog_Register(Engine engine) {
        this.engine = engine;
        init();
    }

    private void init() {
        // Initializes the frame
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);

        // Initializes the components
        txtUsername = new HintTextField("Your username", 23);
        txtDisplayName = new HintTextField("Your display name");

        txtPassword = new JPasswordField();
        txtConfirmPassword = new JPasswordField();

        tipUsername = new ErrorTooltip("Error!!! :)");
        tipPassword = new ErrorTooltip("Error!!! :)");
        tipConfirmPwd = new ErrorTooltip("It's not matched, isn't it?");

        txtFilePath = new JTextField(15);
        txtFilePath.setEditable(false);

        btnSave = new JButton("Sign-up!");
        btnSave.setActionCommand("signup");
        btnSave.setPressedIcon(new ImageIcon(new BufferedImage(1,
                1, BufferedImage.TYPE_INT_ARGB_PRE)));
        btnSave.setVerticalTextPosition(JButton.CENTER);
        btnSave.setHorizontalTextPosition(JButton.CENTER);
        btnSave.setForeground(Color.white);
        btnSave.setFont(MetroStyle.BUTTON_FONT);

        getRootPane().setDefaultButton(btnSave);

        btnCancel = new JTKButton("Cancel?");
        btnCancel.setActionCommand("cancel");
        btnCancel.setPressedIcon(new ImageIcon(new BufferedImage(1,
                1, BufferedImage.TYPE_INT_ARGB_PRE)));
        btnCancel.setVerticalTextPosition(JButton.CENTER);
        btnCancel.setHorizontalTextPosition(JButton.CENTER);
        btnCancel.setFont(MetroStyle.BUTTON_FONT);

        btnFileChooser = new JTKButton("Pick photo");
        btnFileChooser.setActionCommand("pick_photo");
        btnFileChooser.setPressedIcon(new ImageIcon(new BufferedImage(1,
                1, BufferedImage.TYPE_INT_ARGB_PRE)));
        btnFileChooser.setVerticalTextPosition(JButton.CENTER);
        btnFileChooser.setHorizontalTextPosition(JButton.CENTER);
        btnFileChooser.setFont(MetroStyle.SMALL_BUTTON_FONT);
        btnFileChooser.setPreferredSize(new Dimension(btnFileChooser.getPreferredSize().width,
                txtFilePath.getPreferredSize().height));

        // Does layout
        initLayout();
        initListener();
        setResizable(false);
        pack();
        setLocationRelativeTo(null);
    }

    private void initLayout() {
        // Prepares layout
        setLayout(new GridBagLayout());
        GridBagConstraints cons = new GridBagConstraints();
        cons.fill = GridBagConstraints.HORIZONTAL;
        cons.anchor = GridBagConstraints.FIRST_LINE_START;

        cons.gridx = 0;
        cons.gridy = 0;
        cons.insets = new Insets(5, 18, 18, 18);
        add(makeMainPanel(), cons);
    }

    private JPanel makeMainPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        JLabel label;
        Font title = MetroStyle.FORM_TITLE;
        Font header = MetroStyle.FORM_HEADER;
        Insets headerInsets = new Insets(5, 3, 2, 5);
        Insets textFieldInsets = new Insets(4, 5, 4, 5);
        Insets tipInsets = new Insets(3, 0, 6, 5);

        GridBagConstraints cons = new GridBagConstraints();
        cons.fill = GridBagConstraints.HORIZONTAL;
        cons.anchor = GridBagConstraints.FIRST_LINE_START;

        // Start adding components
        cons.gridx = 0;
        cons.gridy = 0;
        cons.gridwidth = 3;
        cons.insets = new Insets(3, 1, 10, 5);
        label = new JLabel("Register :D");
        label.setFont(title);
        label.setForeground(MetroStyle.LIGHTER_MARINE);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = headerInsets;
        cons.gridwidth = 2;
        label = new JLabel("Your username?*");
        label.setFont(header);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = textFieldInsets;
        panel.add(txtUsername, cons);

        cons.gridx += 2;
        cons.insets = tipInsets;
        panel.add(tipUsername, cons);
        tipUsername.setVisible(false);

        cons.gridx = 0;

        cons.gridy++;
        cons.insets = headerInsets;
        label = new JLabel("Your display name?");
        label.setFont(header);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = textFieldInsets;
        panel.add(txtDisplayName, cons);

        cons.gridy++;
        cons.insets = headerInsets;
        label = new JLabel("Your password?*");
        label.setFont(header);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = textFieldInsets;
        panel.add(txtPassword, cons);

        cons.gridx += 2;
        cons.insets = tipInsets;
        panel.add(tipPassword, cons);
        tipPassword.setVisible(false);

        cons.gridx = 0;

        cons.gridy++;
        cons.insets = headerInsets;
        label = new JLabel("Confirm your password*");
        label.setFont(header);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = textFieldInsets;
        panel.add(txtConfirmPassword, cons);

        cons.gridx += 2;
        cons.insets = tipInsets;
        panel.add(tipConfirmPwd, cons);
        tipConfirmPwd.setVisible(false);

        cons.gridx = 0;

        cons.gridy++;
        cons.insets = headerInsets;
        label = new JLabel("Set avatar now?");
        label.setFont(header);
        panel.add(label, cons);

        cons.gridy++;
        cons.insets = textFieldInsets;
        panel.add(txtFilePath, cons);

        cons.gridx += 2;
        panel.add(btnFileChooser, cons);

        cons.gridx = 0;

        cons.gridy++;
        cons.insets = new Insets(25, 4, 4, 6);
        cons.gridwidth = 1;
        cons.weightx = 0.2;
        panel.add(btnSave, cons);

        cons.gridx++;
        cons.insets = new Insets(25, 6, 4, 4);
        cons.weightx = 0.1;
        panel.add(btnCancel, cons);

        return panel;
    }

    private void initListener() {
        txtUsername.addActionListener(this);
        txtDisplayName.addActionListener(this);
        txtPassword.addActionListener(this);
        txtConfirmPassword.addActionListener(this);
        btnSave.addActionListener(this);
        btnCancel.addActionListener(this);
        btnFileChooser.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        boolean signup = true;
        String filePath = null;
        if (cmd.equalsIgnoreCase("signup")) {
            String username = null, displayname = null, password = null;


            if (txtUsername.getText().length() < 4) {

                signup = false;
                tipUsername.setVisible(true);
            } else {

                displayname = txtUsername.getText();
                tipUsername.setVisible(false);
            }
            if (txtDisplayName.getText() == null || txtDisplayName.getText().
                    compareTo("") == 0) {
                displayname = username;
            } else {

                displayname = txtDisplayName.getText();
            }
            if (txtPassword.getText().length() < 4) {
                signup = false;
                tipPassword.setVisible(true);
            } else {
                password = txtPassword.getPassword().toString();
                tipPassword.setVisible(false);
            }
            if (txtPassword.getText().compareTo(txtConfirmPassword.getText()) != 0) {
                signup = false;
                tipConfirmPwd.setVisible(true);
            } else {
                tipConfirmPwd.setVisible(false);
            }
            if (txtFilePath.getText().length() == 0) {
                filePath = MetroStyle.class.getResource("images/contact.png").toString();
                filePath = filePath.substring(6);
                filePath = filePath.replaceAll("%20", " ");
                System.out.println(filePath);

            } else {
                filePath = txtFilePath.getText();
                System.out.println(filePath);
            }
            if (signup) {
                try {

                    Status status = engine.register(txtUsername.getText(), txtPassword.getText(),
                            txtDisplayName.getText(), filePath);

                    if (status.compareTo(Status.USER_EXIST) == 0) {
                        JOptionPane.showMessageDialog(this, "User already exist!!!", "Warning", JOptionPane.WARNING_MESSAGE);
                    } else if (status.compareTo(Status.SERVER_ERROR) == 0) {
                        JOptionPane.showMessageDialog(this, "Error witht users", "Warning", JOptionPane.WARNING_MESSAGE);
                    } else {
                        this.dispose();
                        new Dialog_Login(engine);
                    }
                } catch (RemoteException | FileNotFoundException ex) {

                    Logger.getLogger(Dialog_Register.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else if (cmd.equalsIgnoreCase("cancel")) {
            this.dispose();
        } else if (cmd.equalsIgnoreCase("pick_photo")) {
            JFileChooser fc = new JFileChooser();
            fc.setFileFilter(imageFilter);

            int returnVal = fc.showOpenDialog(Dialog_Register.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                txtFilePath.setText(file.getPath());
            }
        }
    }
}
